package com.bbva.gptf.back.tareas;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Date;

import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;

import com.bbva.gptf.back.dominio.Tgpt037Parametro;
import com.bbva.gptf.back.util.Constantes;
import com.bbva.gptf.back.util.Propiedades;
import com.bbva.gptf.dto.servicio.carga.ServicioCargaInicial;
import com.bbva.jee.arq.spring.core.log.I18nLog;
import com.bbva.jee.arq.spring.core.log.I18nLogFactory;
import com.bbva.jee.arq.spring.core.tareasprogramadas.QuartzTareaCron;

@QuartzTareaCron(nombre="TareaServicioCarga", patronCron="com.bbva.gptf.back.tareas.TareaServicioCarga.patronCron")
public class TareaServicioCarga extends QuartzJobBean
{  
	private static I18nLog log = I18nLogFactory.getLogI18n(TareaServicioCarga.class);
	
	@Autowired
	private ServicioCargaInicial servicioCargaInicial;
	
	public void setServicioCargaInicial(ServicioCargaInicial servicioCargaInicial) {
		this.servicioCargaInicial = servicioCargaInicial;
	}

	@Override
	 protected void executeInternal(JobExecutionContext context) throws JobExecutionException
	 {	
		Tgpt037Parametro parametro = Tgpt037Parametro.findTgpt037Parametro("PROPIEDADES");
		String properties = parametro.getNbValor() + ".properties";
		String nombreServidor = "";
		String comando;
		String line = null;
		String line2 = null;
		try {
			comando = Propiedades.getProperty(Constantes.COMANDO_HOSTNAME, properties);
			final Process proceso = Runtime.getRuntime().exec(comando);
			if (proceso.getErrorStream() != null) {
				final BufferedReader is2 = new BufferedReader(new InputStreamReader(proceso.getErrorStream()));
				final StringBuilder sb2 = new StringBuilder();
				while ((line2 = is2.readLine()) != null) {
					sb2.append(line2);
				}
				log.info("Error ejecutar comando hostname: " + sb2);
			}
			final BufferedReader is = new BufferedReader(new InputStreamReader(proceso.getInputStream()));
			final StringBuilder sb = new StringBuilder();
			while ((line = is.readLine()) != null) {
				sb.append(line);
				nombreServidor = line.trim().toUpperCase();
			}
			log.info("El resultado de comando hostname: " + sb);
			Tgpt037Parametro server = Tgpt037Parametro.findTgpt037Parametro("QUARTZ");
			if (server != null && server.getNbValor().toUpperCase().equals(nombreServidor)) {
				servicioCargaInicial.procesar(false);
				log.info("TareaServicioCarga ejecutada @ "+new Date());
			} else {
				log.info("TareaServicioCarga no ejecutada @ "+new Date());
			}
		} catch (Exception e) {
			log.info("Error en ejecucion de tarea TareaServicioCarga " + e.getMessage());
		}
		
	 } 
}